package com.cnswhy.cloud.server.app.controller.customer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.AliUploadFileUtils;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.core.utils.Kits;
import com.cnswhy.cloud.common.logging.uitls.MDCUtil;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.annotation.RedisLock;
import com.cnswhy.cloud.common.redis.model.LockTimeoutStrategy;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.app.exception.LoginExecption;
import com.cnswhy.cloud.server.app.utils.FileUtil;
import com.cnswhy.cloud.server.app.utils.FtpUtil;
import com.cnswhy.cloud.server.app.utils.RSAUtils;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.*;
import com.cnswhy.cloud.server.common.entity.mq.RegisterMsg;
import com.cnswhy.cloud.server.common.entity.mq.UpdateCustomerSplitMQ;
import com.cnswhy.cloud.server.core.base.BankService;
import com.cnswhy.cloud.server.core.channel.hcpay.dto.BankCardVerifyDto;
import com.cnswhy.cloud.server.core.channel.hcpay.dto.BankCardVerifyResponseDto;
import com.cnswhy.cloud.server.core.channel.hcpay.service.HcpayService;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.dao.WalletTransDtlMapper;
import com.cnswhy.cloud.server.core.dto.CustomerRegistDto;
import com.cnswhy.cloud.server.core.entity.*;
import com.cnswhy.cloud.server.core.oem.SystemService;
import com.cnswhy.cloud.server.core.query.QueryGenerator;
import com.cnswhy.cloud.server.core.service.*;
import com.cnswhy.cloud.server.core.service.app.NoticeReadService;
import com.cnswhy.cloud.server.core.service.customer.CouponDetailService;
import com.cnswhy.cloud.server.core.service.customer.CustomerBankService;
import com.cnswhy.cloud.server.core.service.customer.CustomerService;
import com.cnswhy.cloud.server.core.utils.BaiduAip.Bankcard;
import com.cnswhy.cloud.server.core.utils.BaiduAip.Idcard;
import com.cnswhy.cloud.server.core.utils.PasswordCoder;
import com.cnswhy.cloud.server.core.vo.RespVo;
import com.cnswhy.cloud.server.core.wallet.WalletService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j

@Api(tags = "客户信息管理")
@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController {

    @Autowired
    IntegralLogService integralLogService;
    @Autowired
    NoticeReadService noticeReadService;
    @Autowired
    CustomerService customerService;
    @Autowired
    SpreadLogService spreadLogService;
    @Autowired
    CouponDetailService couponDetailService;
    @Autowired
    WalletService walletService;
    @Autowired
    IdGeneratorService idGeneratorService;
    @Autowired
    CustomerWalletService customerWalletService;
    @Autowired
    SysConfigService sysConfigService;
    @Autowired
    CustomerSplitService customerSplitService;
    @Autowired
    CustomerPhotosService customerPhotosService;
    @Autowired
    HcpayService hcpayService;
    @Autowired
    WalletTransDtlMapper walletTransDtlMapper;
    @Autowired
    VerifyLogService verifyLogService;
    @Autowired
    MessageService messageService;
    @Autowired
    CustomerBankService customerBankService;
    @Autowired
    BankService bankService;
    @Autowired
    SystemService systemService;
    @Autowired
    CustomerUpgradeTransOrderService customerUpgradeTransOrderService;
    @Autowired
    CustomerUpgradeMenuService customerUpgradeMenuService;

    @ApiOperation(value = "修改用户信息", httpMethod = "POST")
    @ApiParam(name = "bo", value = "用户注册BO对象")
    @RequestMapping("/updateCustomer")
    @ResponseBody
    public RespVo updateCustomer(CustomerRegistDto bo, HttpServletRequest request) {
        RespVo respVo = new RespVo();

        try {
            // 验证码校验
            if (!checkVerifyCode(bo.getMobile(), bo.getVerifyCode())) {
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("验证码错误");
                return respVo;
            }

            // 手机号码校验
            Customer entity = new Customer();
            entity.setLoginName(bo.getMobile());
            Customer customer = customerService.queryByLoginName(bo.getMobile());
            if (customer != null && customer.getStatus().intValue() == 1) {
                respVo.setCode(RespVo.CODE_OTHER);
                respVo.setMessage("手机号码重复注册，请直接登录");
                return respVo;
            }

            // 密码解密
            String password = null;
            try {
                password = RSAUtils.decryptString(bo.getPassword());//解密

            } catch (Exception e) {
                log.info("<== RSA解密，异常", e);
            }
            entity.setLoginName(bo.getMobile());
            Customer loginCustomer = getLoginCustomer(request);
            updateCustomer(loginCustomer.getId(),password,null,null,null);
            /*entity.setId(loginCustomer.getId());
            entity.setPassWord(PasswordCoder.generatePassword(password));
            customerService.updateById(entity);*/
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("设置成功");
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("设置失败");
            log.error("设置账号失败", e);
        }
        return respVo;
    }

    /**
     * 设置交易密码
     *
     * @param tradePass 加密密码
     * @param request
     * @return
     */
    @ApiOperation(value = "修改交易密码", httpMethod = "POST")
    @ApiParam(name = "tradePass", value = "交易密码加密数据", required = true)
    @RequestMapping("/saveTradePass")
    @ResponseBody
    public RespVo saveTradePass(String tradePass, HttpServletRequest request) {
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer(request);
            if (loginCustomer == null) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("请先登录");
                return vo;
            }

            // 密码解密
            String password = null;
            password = RSAUtils.decryptString(tradePass);// 解密

            /*
            queryById.setTradePass(PasswordCoder.generatePassword(password));
            customerService.updateById(queryById);*/
            Customer queryById = customerService.queryById(loginCustomer.getId());
            updateCustomer(queryById.getId(),null,null,password,null);
            // 更新session
            redisService.hset(RedisConstant.CUSTOMER_SESSION_KEY, request.getSession().getId(), queryById);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("设置成功");
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("设置交易密码失败");
            log.error("设置交易密码失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "获取登录信息", httpMethod = "POST")
    @RequestMapping("/getLoginData")
    @ResponseBody
    public RespVo getLoginData(HttpServletRequest request) {
        log.info("获取登录信息");

        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            Customer queryById = customerService.queryById(loginCustomer.getId());
            if (StringUtils.isNotBlank(queryById.getHeadImg())
                    && !StringUtils.startsWith(queryById.getHeadImg(), "http")) {
                String prfix = (String) redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.FTP_PATH_PREFIX);
                queryById.setHeadImg(prfix + queryById.getHeadImg());
            }
            CustomerWallet customerWallet = walletService.checkAndCreate(queryById.getId(), WalletType.BALANCE, 0L);
            queryById.setAvailableBalance(CnswhyUtil.getMoney(customerWallet.getAvlbBalance()));
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(queryById));
            List<CustomerWallet> customerWalletList = customerWalletService.list(Wraps.<CustomerWallet>lbQ().eq(CustomerWallet::getCustomerId, queryById.getId()));
            if(customerWalletList.size() != WalletType.values().length){
                for(WalletType walletType : WalletType.values()){
                    boolean exist = false;
                    for(CustomerWallet customerWallet1 : customerWalletList){
                        if(customerWallet1.getWalletType().eq(walletType)){
                            exist = true;
                            break;
                        }
                    }
                    if(!exist){
                        walletService.checkAndCreate(queryById.getId(), walletType, 0L);
                    }
                }
                customerWalletList = customerWalletService.list(Wraps.<CustomerWallet>lbQ().eq(CustomerWallet::getCustomerId, queryById.getId()));
            }
            for(CustomerWallet customerWallet1 : customerWalletList){
                if(WalletType.NO_CARD.eq(customerWallet1.getWalletType())){
                    customerWallet1.setTransferType(1);
                    customerWallet1.setAjaxSpreadLogInType(1);
                    customerWallet1.setAjaxSpreadLogOutType(2);
                }else if(WalletType.REWORD.eq(customerWallet1.getWalletType())){
                    customerWallet1.setTransferType(2);
                    customerWallet1.setAjaxSpreadLogInType(3);
                    customerWallet1.setAjaxSpreadLogOutType(4);
                }else if(WalletType.IOTCL.eq(customerWallet1.getWalletType())){
                    customerWallet1.setTransferType(3);
                    customerWallet1.setAjaxSpreadLogInType(5);
                    customerWallet1.setAjaxSpreadLogOutType(6);
                }
            }
            jsonObject.put("customerWallet", customerWalletList);
            JSONObject vip = new JSONObject();
            CustomerUpgradeTransOrder customerUpgradeTransOrder = customerUpgradeTransOrderService.getOne(Wraps.<CustomerUpgradeTransOrder>lbQ().eq(CustomerUpgradeTransOrder::getCustomerId, queryById.getId())
                    .eq(CustomerUpgradeTransOrder::getStatus,2).eq(CustomerUpgradeTransOrder::getExpired,0));
            if(customerUpgradeTransOrder == null){
                vip.put("pay", false);
            }else{
                vip.put("pay", true);
                vip.put("startDate", customerUpgradeTransOrder.getStartDay());
                vip.put("endDate", customerUpgradeTransOrder.getEndDay());
                vip.put("amount", customerUpgradeTransOrder.getTransAmt());
                vip.put("menuId", customerUpgradeTransOrder.getMenuId());
                vip.put("vipMenu", customerUpgradeMenuService.getById(customerUpgradeTransOrder.getMenuId()).getMenuName());
                //jsonObject.put("vipOrder", customerUpgradeTransOrder);
                //jsonObject.put("vipMenu", );

            }
            jsonObject.put("vip", vip);
            JSONArray jsonArray = new JSONArray();
            JSONObject feeInfo = new JSONObject();
            feeInfo.put("channelType","LITTLE");
            feeInfo.put("feeRate","0.26%");
            feeInfo.put("externFee","1.00");
            jsonArray.add(feeInfo);
            feeInfo = new JSONObject();
            feeInfo.put("channelType","LARGE");
            feeInfo.put("feeRate","0.50%");
            feeInfo.put("externFee","2.00");
            jsonArray.add(feeInfo);
            jsonObject.put("feeInfo", jsonArray);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(jsonObject);
        } catch (LoginExecption e) {
            vo.setCode(-2);
            vo.setMessage("请先登录");
            log.error("获取用户信息失败", e);
        }
        return vo;
    }
    @ApiOperation(value = "获取登录信息", httpMethod = "POST")
    @RequestMapping("/getBalance")
    @ResponseBody
    public RespVo getBalance(HttpServletRequest request,@RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        log.info("获取登录信息");

        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            Page<CustomerWallet> page = new Page<>(currentPage, pageSize);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(customerWalletService.page(page,Wraps.<CustomerWallet>lbQ().eq(CustomerWallet::getCustomerId, loginCustomer.getId())));
        } catch (LoginExecption e) {
            vo.setCode(-2);
            vo.setMessage("请先登录");
            log.error("获取用户信息失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "获取直推信息", httpMethod = "POST")
    @RequestMapping("/queryPushTeam")
    @ResponseBody
    public RespVo queryPushTeam(Customer customer,
                                @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        log.info("获取直推信息");
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            customer.setPromoterId(loginCustomer.getId());
            QueryWrapper<Customer> queryWrapper = QueryGenerator.initQueryWrapper(customer);
            Page<Customer> page = new Page<>(currentPage, pageSize);
            IPage<Customer> pageList = customerService.page(page, queryWrapper);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询团队信息失败");
            log.error("查询团队信息失败", e);
        }
        return vo;
    }
    @ApiOperation(value = "获取直推信息", httpMethod = "POST")
    @RequestMapping("/queryChaorenPushTeam")
    @ResponseBody
    /**
     * type = 0 所有
     * type = 1 黄金
     * type = 2 白银
     * type = 3 青铜
     */
    public RespVo queryChaorenPushTeam(Customer customer,
                                @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                @RequestParam(name = "type", defaultValue = "0") Integer type, HttpServletRequest request) {
        log.info("获取直推信息");
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);

            if(type == 0){
                Customer customer1 = customerService.getById(loginCustomer.getId());
                Page<Customer> page = new Page<>(currentPage, pageSize);
                String likeString = customer1.getPromoterList();
                IPage<Customer> pageList = customerService.getBaseMapper().selectPage(page, Wraps.<Customer>lbQ().ne(Customer::getId, loginCustomer.getId()).likeRight(Customer::getPromoterList, likeString));
                //IPage<Customer> pageList = customerService.page(page, Wraps.<Customer>lbQ().ne(Customer::getId, loginCustomer.getId()).likeRight(Customer::getPromoterList, likeString));
                vo.setResult(pageList);
            }else if(type == 1){
                //黄金
                customer.setPromoterId(loginCustomer.getId());
                QueryWrapper<Customer> queryWrapper = QueryGenerator.initQueryWrapper(customer);
                Page<Customer> page = new Page<>(currentPage, pageSize);
                IPage<Customer> pageList = customerService.page(page, queryWrapper);
                vo.setResult(pageList);
            }else if(type == 2){
                //白银
                List<Customer> customerList = customerService.list(Wraps.<Customer>lbQ().eq(Customer::getPromoterId, loginCustomer.getId()));
                if(customerList.size() > 0){
                    List<Long> ids = new ArrayList<>();
                    for(Customer customer1 : customerList){
                        ids.add(customer1.getId());
                    }
                    Page<Customer> page = new Page<>(currentPage, pageSize);
                    QueryWrapper<Customer> queryWrapper = QueryGenerator.initQueryWrapper(customer);
                    queryWrapper.in("promoter_id",ids );
                    IPage<Customer> pageList = customerService.page(page, queryWrapper);
                    vo.setResult(pageList);
                }else{
                    vo.setResult(null);
                }

            }else if(type == 3) {
                List<Customer> customerList = customerService.list(Wraps.<Customer>lbQ().eq(Customer::getPromoterId, loginCustomer.getId()));
                if(customerList.size() > 0){
                    List<Long> ids = new ArrayList<>();
                    for(Customer customer1 : customerList){
                        ids.add(customer1.getId());
                    }
                    Page<Customer> page = new Page<>(currentPage, pageSize);
                    customerList = customerService.list(Wraps.<Customer>lbQ().in(Customer::getPromoterId,ids));
                    ids = new ArrayList<>();
                    for(Customer customer1 : customerList){
                        ids.add(customer1.getId());
                    }
                    QueryWrapper<Customer> queryWrapper = QueryGenerator.initQueryWrapper(customer);
                    queryWrapper.in("promoter_id",ids );
                    IPage<Customer> pageList = customerService.page(page, queryWrapper);
                    vo.setResult(pageList);
                }else{
                    vo.setResult(null);
                }

            }
            vo.setCode(RespVo.CODE_SUCCESS);

        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询团队信息失败");
            log.error("查询团队信息失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "获取团队信息，不含直推", httpMethod = "POST")
    @RequestMapping("/queryTeam")
    @ResponseBody
    public RespVo queryTeam(Customer customer,
                            @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        log.info("获取团队信息");

        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            Customer customer1 = customerService.getById(loginCustomer.getId());
            Page<Customer> page = new Page<>(currentPage, pageSize);
            String likeString = customer1.getPromoterList();
            IPage<Customer> pageList = customerService.page(page, Wraps.<Customer>lbQ().ne(Customer::getId, customer1.getId()).ne(Customer::getPromoterId, customer1.getId()).likeRight(Customer::getPromoterList, likeString));
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询团队信息失败");
            log.error("查询团队信息失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "上传头像", httpMethod = "POST")
    @ApiParam(name = "file", value = "图片文件", required = true)
    @PostMapping("/uploadHeadImg")
    @ResponseBody
    public RespVo uploadHeadImg(MultipartFile file, HttpServletRequest request) {
        log.info("上传头像");

        RespVo respVo = new RespVo();
        try {
            if (file != null && !file.isEmpty()) {
                // 获取当前登录用户
                Customer customer = this.getLoginCustomer( request);

                //文件类型校验
                String name = file.getOriginalFilename().toString();
                String fileFormat = name.substring(name.lastIndexOf(".") + 1);
                switch (fileFormat.toLowerCase()) {
                    case "jpg":
                    case "jpeg":
                    case "png":
                    case "bmp":
                    case "gif":
                        break;
                    default:
                        respVo.setCode(RespVo.CODE_ERROR);
                        respVo.setMessage("保存失败");
                        respVo.setLogMsg("图片类型不被支持");
                        return respVo;
                }
                // 获取ftp连接信息
                this.getFtpInfo();
                String filePath = dir;

                File toFile = null;
                InputStream ins = null;
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                FileUtil.inputStreamToFile(ins, toFile);
                ins.close();
                //File jpgFile = FileUtil.zipImageFile(toFile);

                // 上传图片
                FtpUtil.upload(toFile, filePath, ipAddr, port, userName, pwd);

                //Customer updateCustomer = new Customer();
                //updateCustomer.setId(customer.getId());
                String headImg =
                        String.valueOf(redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.FTP_PATH_PREFIX))
                                + filePath + toFile.getName();
                //updateCustomer.setHeadImg();
                //customerService.updateById(updateCustomer);
                updateCustomer(customer.getId(),null,null,null,headImg);

                respVo.setCode(RespVo.CODE_SUCCESS);
                respVo.setMessage("上传成功");
                respVo.setResult(
                        String.valueOf(redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.FTP_PATH_PREFIX))
                                + filePath + toFile.getName());
                //jpgFile.deleteOnExit();
            } else {
                respVo.setCode(RespVo.CODE_ERROR);
                respVo.setMessage("上传失败");
            }
        } catch (LoginExecption e) {
            respVo.setCode(RespVo.LOGIN_TIMEOUT);
            respVo.setMessage(e.getMessage());
            log.error("用户未登录，上传异常：", e);
            return respVo;
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("上传失败");
            log.error("上传异常：", e);
        }
        return respVo;
    }

    @ApiOperation(value = "修改昵称", httpMethod = "POST")
    @ApiParam(name = "nickName", value = "昵称", required = true)
    @RequestMapping("/modifyNickName")
    @ResponseBody
    public RespVo modifyNickName(String nickName, HttpServletRequest request) {
        log.info("修改昵称:{}", nickName);

        RespVo vo = new RespVo();
        try {
            if (StringUtils.isEmpty(nickName)) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("昵称不能为空");
                return vo;
            }
            Customer loginCustomer = getLoginCustomer( request);
            updateCustomer(loginCustomer.getId(),null,nickName,null,null);
            /*Customer updateCustomer = new Customer();
            updateCustomer.setId(loginCustomer.getId());
            updateCustomer.setNickName(nickName);
            customerService.updateById(updateCustomer);*/
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("更新成功");
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("更新失败");
            log.error("更新昵称失败", e);
        }
        return vo;
    }


    @ApiOperation(value = "获取收益分页列表", httpMethod = "POST")
    @ApiParam(name = "bo", value = "收益记录bo对象")
    @RequestMapping("/ajaxSpreadLog")
    @ResponseBody
    public RespVo ajaxSpreadLog(@RequestParam(name = "type") Integer type,
                                @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        log.info("获取收益分页列表:{} {} {}", type, currentPage, pageSize);
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            Page<WalletTransDtl> page = new Page<>(currentPage, pageSize);
            IPage<SpreadLog> pageList = walletTransDtlMapper.getSpreadLog(page, loginCustomer.getId(),type);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询失败");
            log.error("查询收益失败");
        }
        return vo;
    }

    @ApiOperation(value = "获取拼购券分页列表", httpMethod = "POST")
    @ApiParam(name = "bo", value = "拼购券明细bo对象")
    @RequestMapping("/ajaxCouponDetail")
    @ResponseBody
    public RespVo ajaxCouponDetail(CouponDetail bo,
                                   @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        log.info("获取拼购券:{} {} {}", JSON.toJSONString(bo), currentPage, pageSize);
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            bo.setCustomerId(loginCustomer.getId());
            QueryWrapper<CouponDetail> queryWrapper = QueryGenerator.initQueryWrapper(bo);
            queryWrapper.orderByDesc("create_time");
            Page<CouponDetail> page = new Page<>(currentPage, pageSize);
            IPage<CouponDetail> pageList = couponDetailService.page(page, queryWrapper);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询失败");
            log.error("查询折扣券明细失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "内转", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型，1 快捷收益转出"),
            @ApiImplicitParam(name = "amount", value = "数量/金额"),
            @ApiImplicitParam(name = "mobile", value = "手机号码，暂时无用")
    })
    @RequestMapping("/transfer")
    @ResponseBody
    public RespVo transfer(Integer type, String amount, String mobile, HttpServletRequest request) {

        log.info("内转:{} {} {}", type, amount, StringUtils.isBlank(mobile) ? "" : mobile);
        RespVo vo = new RespVo();
        try {
            BigDecimal transferAmt = null;
            try {
                transferAmt = BigDecimal.valueOf(Double.parseDouble(amount));
            } catch (NumberFormatException e) {
                throw new BizException("无效转账金额，或者未选择转账金额");
            }
            /*if(amount == null){
            }*/
            if(transferAmt.compareTo(BigDecimal.ZERO) < 0){
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("转出金额小于0");
                return vo;
            }
            Customer loginCustomer = getLoginCustomer( request);
            vo = transferLock(loginCustomer.getId(),type,transferAmt);
        } catch (BizException e) {
            log.error(e.getMessage());
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage(e.getMessage());
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("操作失败");
            log.error("操作失败", e);
        }
        return vo;
    }
    public RespVo transferLock(Long customerId,Integer type,BigDecimal amount){
        Customer customer = customerService.queryById(customerId);
        //发起内转手机号判断次数

        int walletType = 0;
        String sysConfigKey = "";
        boolean transTypeValid = false;
        for(TransferType transferType : TransferType.values()){
            if(type.equals(transferType.getVal())){
                transTypeValid = true;
                break;
            }
        }
        if(!transTypeValid){
            return RespVo.fail("转出类型错误");
        }
        try {
            if (type.equals(TransferType.NO_CARD_BALANCE_TRANSFER.getVal())) {
                walletService.transfer(customer.getId(),WalletType.NO_CARD,TransType.NO_CARD_TRANSFER, CnswhyUtil.getFen(amount) );
            } else if (type.equals(TransferType.REWORD_BALANCE_TRANSFER.getVal())) {
                int limit = systemService.getRewordTransferLimit();
                List<Customer> customerList = customerService.list(Wraps.<Customer>lbQ().eq(Customer::getPromoterId, customer.getId()));
                if(customerList.size() < limit){
                    String message = String.format("直推用户个数未达到%d个,不能转出", limit);
                    throw new BizException(message);
                }
                walletService.transfer(customer.getId(),WalletType.REWORD,TransType.REWORD_TRANSFER, CnswhyUtil.getFen(amount) );
            } else if (type.equals(TransferType.IOTCL_BALANCE_TRANSFER.getVal())) {
                walletService.transfer(customer.getId(),WalletType.IOTCL,TransType.IOTCL_TRANSFER, CnswhyUtil.getFen(amount) );
            }
        } catch (BizException e) {
            return RespVo.fail(e.getMessage());
        } catch (Exception e) {
            return RespVo.fail("未知失败原因");

        }
        return RespVo.success();
    }
    @ApiOperation(value = "更新密码", httpMethod = "POST")
    @ApiParam(name = "newPassword", value = "新密码")
    @PostMapping("/updatePass")
    @ResponseBody
    public RespVo updatePass(String newPassword, HttpServletRequest request) {
        log.info("更新密码:{}", newPassword);

        RespVo respVo = new RespVo();
        try {
            String password = null;
            try {
                newPassword = RSAUtils.decryptString(newPassword);

            } catch (Exception e) {
                log.info("<== RSA解密，异常", e);
            }

            // 从数据库取出客户最新信息
            Customer loginCustomer = getLoginCustomer( request);
            /* entity = new Customer();
            entity.setId(loginCustomer.getId());
            entity.setPassWord(PasswordCoder.generatePassword(password));*/
            // 保存密码修改
            //customerService.updateById(entity);
            updateCustomer(loginCustomer.getId(),password,null,null,null);

            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("修改密码成功");
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("修改密码失败");
            log.error("修改密码异常：", e);
        }
        return respVo;
    }

    @RedisLock(name = "Customer", waitTime = 10,leaseTime = 60,keys = {"#id"},lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
    private Customer updateCustomer(Long id,String password,String nickName,String tradePassword,String headImg){
        Customer customer = customerService.getById(id);
        if(StringUtils.isNotBlank(password)){
            customer.setPassWord(PasswordCoder.generatePassword(password));
        }
        if(StringUtils.isNotBlank(nickName)){
            customer.setNickName(nickName);
        }
        if(StringUtils.isNotBlank(tradePassword)){
            customer.setTradePass(PasswordCoder.generatePassword(tradePassword));
        }
        if(StringUtils.isNotBlank(headImg)){
            customer.setHeadImg(headImg);
        }
        customerService.updateById(customer);
        return customer;
    }

    private boolean checkVerifyCode(String mobile, String verifyCode) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(verifyCode)) {
            return false;
        }

        String redisVerifyCode = (String) redisService.get(RedisConstant.VERIFY_CODE_REDIS_KEY + mobile);
        if (StringUtils.isBlank(redisVerifyCode) || !verifyCode.equals(redisVerifyCode)) {
            return false;
        }
        return true;
    }


    @ApiOperation(value = "判断公告是否已读", httpMethod = "POST")
    @ApiParam(name = "noticeId", value = "公告ID")
    @RequestMapping("/isRead")
    @ResponseBody
    public RespVo isRead(HttpServletRequest request, Long noticeId) {
        log.info("判断公告是否已读:{}", noticeId);

        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            List<NoticeRead> noticeReadList = noticeReadService.list(Wraps.<NoticeRead>lbQ().eq(NoticeRead::getCustomerId, loginCustomer.getId())
                    .eq(NoticeRead::getNoticeId, noticeId));
            if (noticeReadList.size() > 0) {
                vo.setResult(true);
            } else {
                vo.setResult(false);
            }
            vo.setCode(RespVo.CODE_SUCCESS);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询失败");
            log.error("查询失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "保存公告已读", httpMethod = "POST")
    @ApiParam(name = "noticeId", value = "公告ID")
    @RequestMapping("/saveNoticeRead")
    @ResponseBody
    public RespVo saveNoticeRead(HttpServletRequest request, Long noticeId) {
        log.info("保存公告已读:{}", noticeId);

        RespVo vo = new RespVo();
        try {
            NoticeRead entity = new NoticeRead();
            entity.setNoticeId(noticeId);
            Customer loginCustomer = getLoginCustomer( request);
            entity.setCustomerId(loginCustomer.getId());
            noticeReadService.save(entity);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("保存成功");
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("保存失败");
            log.error("保存失败", e);
        }
        return vo;
    }


    @ApiOperation(value = "分页查询贡献值和拼团值", httpMethod = "POST")
    @ApiParam(name = "bo", value = "bo对象")
    @RequestMapping("/ajaxIntegralLog")
    @ResponseBody
    public RespVo ajaxIntegralLog(Integer integralType,Integer type,
                                  @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                  HttpServletRequest req) {
        log.info("分页查询贡献值和拼团值:{}", type, currentPage, pageSize);

        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer(req);
            //integralLog.setCustomerId(loginCustomer.getId());
            //integralLog.setCustomerId(loginCustomer.getId());
            //PagerVo<IntegralLog> queryPageData = integralLogService.queryPageData(bo);
            //QueryWrapper<IntegralLog> queryWrapper = QueryGenerator.initQueryWrapper(integralLog);
            //queryWrapper.orderByDesc("create_date");
            Page<WalletTransDtl> page = new Page<>(currentPage, pageSize);
            if(type == null){
                type = integralType;
            }
            IPage<IntegralLog> pageList = walletTransDtlMapper.getIntegralLog(page, loginCustomer.getId(),type);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
            //vo.setResult(queryPageData);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询失败");
            log.error("查询失败", e);
        }
        return vo;
    }

    @Autowired
    RedisService redisService;

    @ApiOperation(value = "获取客服URL", httpMethod = "POST")
    @RequestMapping("/getCustomerServiceUrl")
    @ResponseBody
    public RespVo getCustomerServiceUrl() {
        log.info("获取客服URL:{}");
        RespVo vo = new RespVo();
        String hget = (String) redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.CUSTOMER_SERVICE_URL);
        vo.setCode(RespVo.CODE_SUCCESS);
        vo.setResult(hget);
        return vo;
    }

    @ApiOperation(value = "获取提现配置", httpMethod = "POST")
    @RequestMapping("/getWalletInfo")
    @ResponseBody
    public RespVo getWalletInfo() {
        log.info("获取提现信息:{}");
        RespVo vo = new RespVo();
        SysConfig sysConfig = sysConfigService.getOne(Wraps.<SysConfig>lbQ().eq(SysConfig::getConfigKey, "wallet_amt"));
        vo.setResult(sysConfig);
        vo.setCode(RespVo.CODE_SUCCESS);
        return vo;
    }
    @ApiOperation(value = "自定义费率", httpMethod = "POST")
    @RequestMapping("/setSplit")
    @ResponseBody
    public RespVo setSplit(Long split, HttpServletRequest request, Long downCustomerId, String downCustomertPhone) {
        log.info("设置自定义费率:{} {} {}", split, downCustomerId, downCustomertPhone);
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            CustomerSplit currSplit = customerSplitService.getOne(Wraps.<CustomerSplit>lbQ().eq(CustomerSplit::getDownCustomerId,loginCustomer.getId()));
            if(currSplit.getSplitRate() <= 0){
                throw new BizException("上级未设置本级服务商收益");
            }
            CustomerSplit customerSplit = customerSplitService.getOne(Wraps.<CustomerSplit>lbQ().eq(CustomerSplit::getCustomerId,loginCustomer.getId())
                    .eq(CustomerSplit::getDownCustomerId,downCustomerId));
            if(customerSplit == null){
                customerSplit = new CustomerSplit();
                customerSplit.setCustomerId(loginCustomer.getId());
                customerSplit.setSplitRate(0L);
                customerSplit.setDownCustomerId(downCustomerId);
                customerSplit.setDownCustomerPhone(downCustomertPhone);
                customerSplit.setStatus("0");
                customerSplit.setSplitType(SplitType.NO_CARD);
                customerSplitService.save(customerSplit);
            }
            if(split.compareTo(100L) > 0 || split.compareTo(0L) < 0){
                throw new BizException("下级费率设置在0-100间");
            }
            /*if(customerSplit.getSplitRate().compareTo(split) > 0){
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("操作失败:自定义费率不能调低");
                return vo;
            }*/
            /*if(customer.getPromoterId() == null){
                CustomerSplit promoterSPlit = customerSplitService.getOne(Wraps.<CustomerSplit>lbQ().eq(CustomerSplit::getDownCustomerId,customer.getId()));
                if(promoterSPlit == null || "0".equals(promoterSPlit.getStatus())){
                    vo.setCode(RespVo.CODE_ERROR);
                    vo.setMessage("操作失败:运营未开通自定义费率");
                    return vo;
                }
                if(split.compareTo(promoterSPlit.getSplitRate()) > 0){
                    vo.setCode(RespVo.CODE_ERROR);
                    vo.setMessage("操作失败:自定义费率不能超过上级费率");
                    return vo;
                }
            }else{
                CustomerSplit promoterSPlit = customerSplitService.getOne(Wraps.<CustomerSplit>lbQ().eq(CustomerSplit::getDownCustomerId,customer.getId()));
                if(promoterSPlit == null || "0".equals(promoterSPlit.getStatus())){
                    vo.setCode(RespVo.CODE_ERROR);
                    vo.setMessage("操作失败:上级未设定自定义费率");
                    return vo;
                }else{
                    if(split.compareTo(promoterSPlit.getSplitRate()) > 0){
                        vo.setCode(RespVo.CODE_ERROR);
                        vo.setMessage("操作失败:自定义费率不能超过上级费率");
                        return vo;
                    }
                }
            }*/
            customerSplit.setSplitRate(split);
            customerSplit.setStatus("1");
            customerSplit.setCurrRate(currSplit.getCurrRate().multiply(BigDecimal.valueOf(split.doubleValue() / 100)));
            customerSplit.setUpRate(currSplit.getCurrRate().subtract( customerSplit.getCurrRate()));
            customerSplitService.updateById(customerSplit);
            //更新分润链
            UpdateCustomerSplitMQ updateCustomerSplitMQ = UpdateCustomerSplitMQ.builder().customerId(customerSplit.getDownCustomerId()).build();
            messageService.sendQueueByObject(AmqpExchange.UPDATE_CUSTOMER_SPLIT_MESSAGE,updateCustomerSplitMQ);
            vo.setCode(RespVo.CODE_SUCCESS);
        } catch (BizException e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage(e.getMessage());
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("操作失败");
            log.error("操作失败", e);
        }
        return vo;
    }
    @ApiOperation(value = "查询自定义费率及上级自定义费率", httpMethod = "POST")
    @RequestMapping("/getSplit")
    @ApiParam(name = "type", value = "1:已设置 0:未设置")
    @ResponseBody
    public RespVo getSplit(HttpServletRequest request, String type) {
        SplitType splitType = SplitType.NO_CARD;
        log.info("查询自定义费率及上级自定义费率:{}",type);
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            //Customer customer = customerService.queryById(loginCustomer.getId());

            //查询出所有下级
            List<Customer> customers = customerService.list(Wraps.<Customer>lbQ().eq(Customer::getPromoterId, loginCustomer.getId()));
            List<CustomerSplit> customerSplitList = customerSplitService.list(Wraps.<CustomerSplit>lbQ().eq(CustomerSplit::getCustomerId, loginCustomer.getId()).eq(CustomerSplit::getSplitType,splitType));
            JSONObject jsonObject = new JSONObject();
            if (customers.size() == customerSplitList.size()) {
                if ("1".equals(type)) {
                    //List<CustomerSplit> customerSplitSet = customerSplitService.list(Wraps.<CustomerSplit>lbQ().eq(CustomerSplit::getCustomerId, loginCustomer.getId()).eq(CustomerSplit::getStatus, "1").eq(CustomerSplit::getSplitType,splitType));
                    List<CustomerSplit> customerSplitSet = customerSplitService.getVerifyList(loginCustomer.getId(),"1",splitType);
                    jsonObject.put("customerSplit", customerSplitSet); // 自定义费率
                } else {
                    List<CustomerSplit> customerSplitSet = customerSplitService.getVerifyList(loginCustomer.getId(),"0",splitType);
                    jsonObject.put("customerSplit", customerSplitSet); // 自定义费率
                }
            } else {
                List<Long> customerSplitListId = new ArrayList<>();
                //先遍历下级用户  没有记录就填充
                for (CustomerSplit customerSplit : customerSplitList) {
                    customerSplitListId.add(customerSplit.getDownCustomerId());
                }
                for (Customer customer : customers) {
                    if (customerSplitListId.contains(customer.getId().toString()) == false) {
                        //没有记录
                        CustomerSplit customerSplit = new CustomerSplit();
                        customerSplit.setCustomerId(loginCustomer.getId());
                        customerSplit.setSplitRate(0L);
                        customerSplit.setSplitType(splitType);
                        customerSplit.setDownCustomerId(customer.getId());
                        customerSplit.setDownCustomerPhone(customer.getLoginName());
                        customerSplit.setStatus("0");
                        customerSplitService.save(customerSplit);
                    }
                }
                if ("1".equals(type)) {
                    List<CustomerSplit> customerSplitSet = customerSplitService.getVerifyList(loginCustomer.getId(),"1",splitType);
                    jsonObject.put("customerSplit", customerSplitSet); // 自定义费率
                } else {
                    List<CustomerSplit> customerSplitSet = customerSplitService.getVerifyList(loginCustomer.getId(),"0",splitType);
                    jsonObject.put("customerSplit", customerSplitSet); // 自定义费率
                }
            }
            BigDecimal limitSplit = null;
            CustomerSplit promoterSPlit = customerSplitService.getOne(Wraps.<CustomerSplit>lbQ().eq(CustomerSplit::getDownCustomerId,loginCustomer.getId()).eq(CustomerSplit::getSplitType,splitType));
            if(promoterSPlit == null || "0".equals(promoterSPlit.getStatus())){
                limitSplit = BigDecimal.ZERO;
            }else{
                limitSplit = promoterSPlit.getCurrRate();
            }
            jsonObject.put("limitSplit", limitSplit);
            vo.setResult(jsonObject);
            vo.setCode(RespVo.CODE_SUCCESS);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("操作失败");
            log.error("操作失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "上传头像(ali)", httpMethod = "POST")
    @ApiParam(name = "file", value = "图片文件", required = true)
    @PostMapping("/aliUploadHeadImg")
    @ResponseBody
    public RespVo aliUploadHeadImg(MultipartFile file, HttpServletRequest request) {
        log.info("上传头像aliUploadHeadImg");

        RespVo respVo = new RespVo();
        try {
            if (file != null && !file.isEmpty()) {
                //文件类型校验
                String name = file.getOriginalFilename().toString();
                String fileFormat = name.substring(name.lastIndexOf(".") + 1);
                switch (fileFormat.toLowerCase()) {
                    case "jpg":
                    case "jpeg":
                    case "png":
                    case "bmp":
                    case "gif":
                        break;
                    default:
                        respVo.setCode(RespVo.CODE_ERROR);
                        respVo.setMessage("保存失败");
                        respVo.setLogMsg("图片类型不被支持");
                        return respVo;
                }
                // 获取当前登录用户
                Customer customer = this.getLoginCustomer( request);
                String imageName = "head.jpg";
                imageName = Kits.Date.getyyyyMMddHHmmss() + customer.getId() + imageName;
                String photosUrl = AliUploadFileUtils.updateLoadFileToOss(file, imageName);

                updateCustomer(customer.getId(), null, null, null, photosUrl);
                respVo.setCode(RespVo.CODE_SUCCESS);
                respVo.setMessage("上传成功");
                respVo.setResult(photosUrl);
            } else {
                respVo.setCode(RespVo.CODE_ERROR);
                respVo.setMessage("上传失败");
            }
        } catch (LoginExecption e) {
            respVo.setCode(RespVo.LOGIN_TIMEOUT);
            respVo.setMessage(e.getMessage());
            log.error("用户未登录，上传异常：", e);
            return respVo;
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("上传失败");
            log.error("上传异常：", e);
        }
        return respVo;
    }

    @ApiOperation(value = "图片上传", httpMethod = "POST")
    @ApiParam(name = "file", value = "图片文件type(00:人像面 01:国徽面 02:储蓄卡正面)", required = true)
    @PostMapping("/aliUploadImg")
    @ResponseBody
    public RespVo aliUploadImg(MultipartFile file, HttpServletRequest request, String type) {
        log.info("图片上传aliUploadImg:{} {}", type,file.getOriginalFilename());
        RespVo respVo = new RespVo();
        if (StringUtils.isBlank(type)) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("图片类型为空");
        }
        try {
            if (file != null && !file.isEmpty()) {
                String name = file.getOriginalFilename().toString();
                String fileFormat = name.substring(name.lastIndexOf(".") + 1);
                switch (fileFormat.toLowerCase()) {
                    case "jpg":
                    case "jpeg":
                    case "png":
                    case "bmp":
                    case "gif":
                        break;
                    default:
                        respVo.setCode(RespVo.CODE_ERROR);
                        respVo.setMessage("保存失败");
                        respVo.setLogMsg("图片类型不被支持");
                        return respVo;
                }
                //文件类型校验
                // 获取当前登录用户
                Customer customer = this.getLoginCustomer( request);
                String imageName = "merch.jpg";
                imageName = customer.getId() + type + Kits.Date.getyyyyMMddHHmmss() + imageName;
                String photosUrl = AliUploadFileUtils.updateLoadFileToOss(file, imageName);

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("imgPath", photosUrl);

                IdCardResults idCardResults = new IdCardResults();
                JSONObject jsonObject1 = new JSONObject();
                switch (type) {
                    case "00":
                        idCardResults = Idcard.identify(photosUrl);

                        if (idCardResults == null || idCardResults.getWords_result() == null) {
                            log.info("图片识别不出");
                            throw new BizException(-1, "图片识别不出");
                        }
                        if (StringUtils.isEmpty(idCardResults.getWords_result().getIdNo().getWords())) {
                            log.info("身份证号识别不出");
                            throw new BizException(-1, "身份证号识别不出");
                        }
                        if (StringUtils.isEmpty(idCardResults.getWords_result().getName().getWords())) {
                            log.info("姓名识别不出");
                            throw new BizException(-1, "姓名识别不出");
                        }
                        jsonObject1 = new JSONObject();
                        jsonObject1.put("idNo", idCardResults.getWords_result().getIdNo().getWords().trim().replace(" ", ""));
                        jsonObject1.put("name", idCardResults.getWords_result().getName().getWords().trim().replace(" ", ""));
                        jsonObject.put("idBean", jsonObject1);

                        break;
                    case "01":
                        idCardResults = Idcard.identifyBack(photosUrl);

                        if (idCardResults == null || idCardResults.getWords_result() == null) {
                            log.info("图片识别不出");
                            throw new BizException(-1, "图片识别不出");
                        }
                        if (StringUtils.isEmpty(idCardResults.getWords_result().getEffectDate().getWords())) {
                            log.info("生效日期为空");
                            throw new BizException(-1, "生效日期为空");
                        }
                        if (StringUtils.isEmpty(idCardResults.getWords_result().getInvalidDate().getWords())) {
                            log.info("生效日期为空");
                            throw new BizException(-1, "生效日期为空");
                        }
                        if (StringUtils.isEmpty(idCardResults.getWords_result().getAgency().getWords())) {
                            log.info("签发机构为空");
                            throw new BizException(-1, "签发机构为空");
                        }
                        jsonObject1 = new JSONObject();
                        jsonObject1.put("effectDate", idCardResults.getWords_result().getEffectDate().getWords().trim());
                        jsonObject1.put("invalidDate", idCardResults.getWords_result().getInvalidDate().getWords().trim());
                        jsonObject1.put("agency", idCardResults.getWords_result().getAgency().getWords().trim());
                        jsonObject.put("idBean", jsonObject1);

                        break;
                    case "02":
                        BankCardResult bankCardResult;
                        bankCardResult = Bankcard.identify(photosUrl);

                        String cardNo = "";
                        if (bankCardResult.getResult() != null && !org.apache.commons.lang3.StringUtils.isEmpty(bankCardResult.getResult().getBank_card_number())) {
                            cardNo = bankCardResult.getResult().getBank_card_number().trim().replace(" ", "");
                        }
                        String bankName = "";
                        if (bankCardResult.getResult() != null && !org.apache.commons.lang3.StringUtils.isEmpty(bankCardResult.getResult().getBank_name())) {
                            bankName = bankCardResult.getResult().getBank_name().trim().replace(" ", "");
                        }
                        int bankType = 1;
                        if (bankCardResult.getResult() != null && bankCardResult.getResult().getBank_card_type() > 0) {
                            bankType = bankCardResult.getResult().getBank_card_type();
                        }
                        jsonObject1 = new JSONObject();
                        jsonObject1.put("cardNo", cardNo);
                        jsonObject1.put("bankName", bankName);
                        jsonObject1.put("bankType", bankType);
                        jsonObject.put("bankCardBean", jsonObject1);

                        break;
                    case "03":
                        break;
                    case "99":
                        //商户图片上传
                        break;
                }
                //入库
                CustomerPhotos customerPhotos = new CustomerPhotos();
                customerPhotos.setCustomerId(customer.getId());
                customerPhotos.setImgName(imageName);
                customerPhotos.setImgPath(photosUrl);
                customerPhotos.setImgType(type);
                CustomerPhotos customerPhotos1 = customerPhotosService.getOne(Wraps.<CustomerPhotos>lbQ().eq(CustomerPhotos::getCustomerId, customer.getId()).eq(CustomerPhotos::getImgType, type));
                if (customerPhotos1 == null) {
                    customerPhotosService.save(customerPhotos);
                } else {
                    customerPhotosService.update(customerPhotos, Wraps.<CustomerPhotos>lbQ().eq(CustomerPhotos::getCustomerId, customer.getId()).eq(CustomerPhotos::getImgType, type));
                }

                respVo.setCode(RespVo.CODE_SUCCESS);
                respVo.setMessage("上传成功");
                respVo.setResult(jsonObject);
            } else {
                respVo.setCode(RespVo.CODE_ERROR);
                respVo.setMessage("上传失败");
            }
        } catch (LoginExecption e) {
            respVo.setCode(RespVo.LOGIN_TIMEOUT);
            respVo.setMessage(e.getMessage());
            log.error("用户未登录，上传异常：", e);
            return respVo;
        } catch (BizException e) {
            respVo.setCode(e.getCode());
            respVo.setMessage(e.getMessage());
            log.error("上传异常：", e.getMessage());
            return respVo;
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("上传失败");
            log.error("上传异常：", e);
        }
        return respVo;
    }

    @ApiOperation(value = "四要素认证", httpMethod = "POST")
    @RequestMapping("/bankCardVerify")
    @ApiParam(name = "c", value = "用户对象", required = true)
    @ResponseBody
    public RespVo bankCardVerify(HttpServletRequest request, VerifyLog c) {
        log.info("四要素认证:{}", JSON.toJSONString(c));
        RespVo vo = new RespVo();
        if (StringUtils.isBlank(c.getVerifyCard())) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("卡号为空");
            return vo;
        }
        if(!CnswhyUtil.checkBankCard(c.getVerifyCard())){
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("卡号校验失败");
            return vo;
        }
        if (StringUtils.isBlank(c.getVerifyIdno())) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("身份证为空");
            return vo;
        }

        if(!CnswhyUtil.idNumCheck(c.getVerifyIdno())){
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("身份证校验失败");
            return vo;
        }
        if (StringUtils.isBlank(c.getVerifyPhone())) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("手机号为空");
            return vo;
        }
        if (StringUtils.isBlank(c.getVerifyName())) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("姓名为空");
            return vo;
        }
        Customer customer = this.getLoginCustomer( request);
        List<Customer> customer1 = customerService.list(Wraps.<Customer>lbQ().eq(Customer::getVerifyIdNo, c.getVerifyIdno()));
        if (customer1.size() > 0) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("该身份已注册,请用注册账号登录！");
        }
        BankCardVerifyResponseDto bankCardVerifyResponseDto = hcpayService.bankCardVerify(BankCardVerifyDto.builder()
                .cardId(c.getVerifyCard())
                .name(c.getVerifyName())
                .idNo(c.getVerifyIdno())
                .phone(c.getVerifyPhone())
                .orderId("verify" + Kits.Date.getyyyyMMddHHmmss() + Kits.Random.getRandom(1000, 10000)).build(), "882035716004024");
        c.setCustomerId(customer.getId());
        c.setInsertDate(Kits.Date.getyyyyMMdd());
        c.setRespCode(bankCardVerifyResponseDto.getRespCode());
        c.setRespDesc(bankCardVerifyResponseDto.getRespDesc());
        c.setStatus("0");
        verifyLogService.save(c);
        if (bankCardVerifyResponseDto.getOrderStatus().equals("02")) {
            if(!"1".equals(customer.getVerifyStatus())){
                customer.setVerifyStatus("1");
                RegisterMsg registerMsg = RegisterMsg.builder().customerId(customer.getId())
                        .customerType(customer.getCustomerType())
                        .promoterMobile(customer.getPromoterMobile())
                        .loginName(customer.getLoginName())
                        .nickName(customer.getNickName())
                        .promoterId(customer.getPromoterId())
                        .verifyStatus(customer.getVerifyStatus())
                        .realName(customer.getRealName()).build();
                registerMsg.setTraceId(MDCUtil.getTraceId());
                messageService.sendQueueByObject(AmqpExchange.VERIFY_MESSAGE, registerMsg);
            }
            customer.setVerifyCard(c.getVerifyCard());
            customer.setVerifyIdNo(c.getVerifyIdno());
            customer.setVerifyPhone(c.getVerifyPhone());
            customer.setVerifyName(c.getVerifyName());
            customerService.updateById(customer);

            c.setStatus("1");
            verifyLogService.updateById(c);

            CustomerBank customerBank = customerBankService.getOne(Wraps.<CustomerBank>lbQ().eq(CustomerBank::getBankNum,customer.getVerifyCard()).eq(CustomerBank::getCustomerId,customer.getId()));
            if(customerBank != null) {
                customerBank.setMobile(customer.getVerifyPhone());
                customerBankService.updateById(customerBank);
            }else if(customerBank == null){
                customerBank = new CustomerBank();
                customerBank.setCustomerId(customer.getId());
                customerBank.setBankNum(customer.getVerifyCard());
                customerBank.setMobile(customer.getVerifyPhone());
                customerBank.setIdCard(customer.getVerifyIdNo());
                customerBank.setAccountName(customer.getVerifyName());
                try {
                    BaseBankBin baseBankBin = bankService.getBankBinByCardId(customerBank.getBankNum());
                    if("00".equals(baseBankBin.getCardType())){
                        customerBank.setCardType(BankCardType.UNKNOWN.getVal());
                    }else if("01".equals(baseBankBin.getCardType())){
                        customerBank.setCardType(BankCardType.DEBIT_CARD.getVal());
                    }else if("02".equals(baseBankBin.getCardType())){
                        customerBank.setCardType(BankCardType.CREDIT_CARD.getVal());
                    } else if("03".equals(baseBankBin.getCardType())){
                        customerBank.setCardType(BankCardType.SEMI_CREDIT_CARD.getVal());
                    }else if("04".equals(baseBankBin.getCardType())){
                        customerBank.setCardType(BankCardType.DEBIT_CREDIT_CARD.getVal());
                    }else if("05".equals(baseBankBin.getCardType())){
                        customerBank.setCardType(BankCardType.PREPAID_CARD.getVal());
                    }
                    customerBank.setBankAbbr(baseBankBin.getBankAbbr());
                    customerBank.setBankName(baseBankBin.getBankName());
                } catch (BizException e) {
                    customerBank.setCardType(BankCardType.UNKNOWN.getVal());
                }
                List<CustomerBank> queryPage = customerBankService.getCustomerBankList(customer.getId());
                if(queryPage != null && queryPage.size() < 1 && (BankCardType.DEBIT_CARD.getVal() == customerBank.getCardType().intValue())){
                    customerBank.setIsDefault(1);
                }else{
                    customerBank.setIsDefault(0);
                }
                customerBankService.save(customerBank);
            }
            vo.setResult("认证成功");
            vo.setCode(RespVo.CODE_SUCCESS);
            return vo;
        } else {
            vo.setMessage(bankCardVerifyResponseDto.getRespDesc());
            vo.setCode(RespVo.CODE_ERROR);
            return vo;
        }
    }
}
